Home > database >  printing only specific lines with sed
printing only specific lines with sed

Time:11-21

I have following File (wishlist.txt):

Alligatoah Musik_ist_keine_lösung;https:///uhfhf
Alligatoah STRW;https:///uhfhf?i
Amewu Entwicklungshilfe;https:///uhfhf?i

and want to have the first word of line n. so for n = 1:

Alligatoah

What i have so far is:

sed -e 's/\s.*//g' wishlist.txt

is there a elegant way to get rid of all lines except n?

Edit:

How to pass a bash variable "$i" to sed since

sed -n '$is/ .*//p' $wishlist

and

sed -n "\`${i}\`s/ .*//p" $wishlist

doesn't work

CodePudding user response:

A couple of other techniques to get the first word of the 3rd line:

awk -v line=3 'NR == line {print $1; exit}' file

or

head -n 3 file | tail -n 1 | cut -d ' ' -f 1

CodePudding user response:

sed supports "addresses", so you can tell it what lines to operate on. To print only the first line, you can use

sed -e '1!d; s/\s.*//g'

where 1!d means: on lines other then 1, delete the line.

CodePudding user response:

Something like this. For the 1st word of the 3rd line.

sed -n '3s/\s.*//p' wishlist.txt

To use a variable: Note: Double quotes.

line=3; sed -n "${line}s/\s.*//p" wishlist.txt
  • Related