Get Nth line in file after parsing another file

I have one of my large files as

foo:43:sdfasd:daasf
bar:51:werrwr:asdfa
qux:34:werdfs:asdfa
foo:234:dfasdf:dasf
qux:345:dsfasd:erwe
...............

here is the 1st column foo, bar and qux, etc. are file names. and the second column 43.51, 34, etc. are line numbers. I want to print the Nth line (indicated by the second column) for each file (indicated in the 1st column). How can I automate the above in a unix shell. Actually above the file is created at compile time, and I want to print a warning line in the code.

-Thank,

+3
source share
6 answers
while IFS=: read name line rest
do
    head -n $line $name | tail -1
done < input.txt
+2
source

while IFS=: read file line message; do
    echo "$file:$line - $message:"
    sed -n "${line}p" "$file"
done <yourfilehere
+2
source
awk 'NR==4 {print}' yourfilename

or

cat yourfilename | awk 'NR==4 {print}'

4- . .

0
 sed -nr '3{s/^([^:]*):([^:]*):.*$/\1 \2/;p}' namesNnumbers.txt 
 qux 34
  • -n ,
  • -r ( parens)
  • 3 do {...; p} ( )
  • s ubstitute foobarbaz foo bar

, :

fnUln=$(sed -nr '3{s/^([^:]*):([^:]*):.*$/\1 \2/;p}' namesNnumbers.txt)

fn=$(echo ${fnUln/ */})
ln=$(echo ${fnUln/* /})
sed -n "${ln}p" "$fn"
0
source

Just awk, but probably worse than @kev or @MarkReed answers. However, it processes each file only once. GNU awk required

gawk -F: '
    BEGIN {OFS=FS}
    { 
        files[$1] = 1
        lines[$1] = lines[$1] " " $2
        msgs[$1, $2] = $3 
    }
    END {
        for (file in files) {
            split(lines[file], l, " ")
            n = asort(l)
            count = 0
            for (i=1; i<=n; i++) {
                while (++count <= l[i])
                    getline line < file
                print file, l[i], msgs[file, l[i]]
                print line
            }
            close(file)
        }
    }
'
0
source

This might work for you:

sed 's/^\([^,]*\),\([^,]*\).*/sed -n "\2p" \1/' file |
sort -k4,4 | 
sed ':a;$!N;s/^\(.*\)\(".*\)\n.*"\(.*\)\2/\1;\3\2/;ta;P;D' |
sh
0
source

All Articles