简体   繁体   中英

sed retrieve part of line

I have lines of code that look like this:

hi:12345:234 (second line)

How do I write a line of code using the sed command that only prints out the 2nd item in the second line?

My current command looks like this:

sed -n '2p' file which gets the second line, but I don't know what regex to use to match only the 2nd item '12345' and combine with my current command

Could you please try following, written and tested with shown samples in GNU sed .

sed -n '2s/\([^:]*\):\([^:]*\).*/\2/p' Input_file

Explanation: Using -n option of sed will stop the printing for all the lines and printing will happen only for those lines where we are explicitly mentioning p option to print(later in code). Then mentioning 2s means perform substitution on 2nd line only. Then using regex and sed 's capability to store matched regex into a temp buffer by which values can be retrieved later by numbering 1,2...and so on . Regex is basically catching 1st part which comes before first occurrence of : and then 2nd part after first occurrence of : to till 2nd occurrence of : as per OP's request. So while doing substitution mentioning /2 will replace whole line with 2nd value stored in buffer as per request, then mentioning p will print that part only in 2nd line.

A couple of solutions:

echo "hi:12345:234" | sed -n '2s/.*:\([0-9]*\):.*/\1/p'
echo "hi:12345:234" | sed -n '2{s/^[^:]*://; s/:.*//p; q}'
echo "hi:12345:234" | awk -F':' 'FNR==2{print $2}'

All display 12345 .

sed -n '2s/.*:\([0-9]*\):.*/\1/p' only displays the captured value thanks to -n and p option/flag. It matches a whole string capturing digits between two colons, \1 only keeps the capture.

The sed -n '2{s/^[^:]*://;s/:.*//p;q}' removes all from start till first : , all from the second to end, and then quits ( q ) so if your file is big, it will be processed quicker.

awk -F':' 'FNR==2{print $2}' splits the second line with a colon and fetches the second item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM