definitiv
definitiv

Reputation: 5

printing only specific lines with sed

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

Upvotes: 0

Views: 2561

Answers (3)

choroba
choroba

Reputation: 241768

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.*//'

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

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246744

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

Upvotes: 3

Darkman
Darkman

Reputation: 2981

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

Upvotes: 1

Related Questions