Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select multiple lines from a file or from pipe in a script?

I'd like to have a script, called lines.sh that I can pipe data to to select a series of lines.

For example, if I had the following file:

test.txt

a 
b
c
d

Then I could run:

cat test.txt | lines 2,4

and it would output

b
d

I'm using zsh, but would prefer a bash solution if possible.

like image 345
Brad Parks Avatar asked Dec 16 '14 16:12

Brad Parks


People also ask

How do you select multiple lines in Shell?

Place your cursor somewhere in or next to the first word you wish to select. While holding down Ctrl (Windows & Linux) or Command (Mac OS X), click in the next word you wish to select.

How do I input multiple lines in bash?

Doing: #!/bin/bash read -e -p "Multiline input=" variable; printf "'variable=%s'" "${variable}"; Typing 'multi\nline' on Multiline input= makes printf output 'variable=multinline' Typing 'multi\\nline' on Multiline input= makes printf output 'variable=multi\nline'

How do you select a line in shell script?

Press Home key to get to the start of the line. For Selecting multiple lines, use Up/Down key.


1 Answers

You can use this awk:

awk -v s='2,4' 'BEGIN{split(s, a, ","); for (i in a) b[a[i]]} NR in b' file
two
four

Via a separate script lines.sh:

#!/bin/bash
awk -v s="$1" 'BEGIN{split(s, a, ","); for (i in a) b[a[i]]} NR in b' "$2"

Then give execute permissions:

chmod +x lines.sh

And call it as:

./lines.sh '2,4' 'test.txt'
like image 99
anubhava Avatar answered Sep 22 '22 14:09

anubhava