Skip to main content
1 of 4
Kusalananda
  • 355.9k
  • 42
  • 735
  • 1.1k

The issue with your code is that you try to run a sed command that ooks like

2 5 7 10p

This obviously makes no sense to sed, so it complains.

Part of your issue is using a single string to hold many different items (the line numbers). This is better done with an array. Each array element (line number) will then need to have a p inserted after it to make it a separate sed command.

For the numbers 2, 5, 7, and 10, you want a sed script that looks something like

2p; 5p; 7p; 10p;

(where the spaces are optional and where each ; could be replaced by a literal newline, which is what we do below).

You can create a script like that rather easily from an array in bash:

lines=( 2 5 7 10 )
printf '%sp\n' "${lines[@]}" | sed -n -f /dev/stdin longText.txt

This uses printf to create a sed script from the list of numbers, and feeds it to sed which reads it from standard input with -f /dev/stdin, and applies it to you file.

Kusalananda
  • 355.9k
  • 42
  • 735
  • 1.1k