3

I have one of my large file as

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

here 1st column foo, bar and qux etc. are file names. and 2nd column 43,51, 34 etc. are line numbers. I want to print Nth line(specified by 2nd column) for each file(specified in 1st column). How can I automate above in unix shell. Actually above file is generated while compiling and I want to print warning line in code.

-Thanks,

4

6 回答 6

2

while IFS=: read file line message; do
    echo "$file:$line - $message:"
    sed -n "${line}p" "$file"
done <yourfilehere
于 2012-04-13T16:48:50.607 回答
2
while IFS=: read name line rest
do
    head -n $line $name | tail -1
done < input.txt
于 2012-04-13T14:46:18.640 回答
0
awk 'NR==4 {print}' yourfilename

or

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

以上将适用于文件中的第 4 行。您可以根据需要更改数字。

于 2012-04-13T14:45:05.603 回答
0
 sed -nr '3{s/^([^:]*):([^:]*):.*$/\1 \2/;p}' namesNnumbers.txt 
 qux 34
  • -n 默认不输出,
  • -r 正则表达式(使用括号简化)
  • 在第 3 行做 {...;p} (最后打印)
  • 用 foo bar 代替 foobarbaz

所以要使用这些值:

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

fn=$(echo ${fnUln/ */})
ln=$(echo ${fnUln/* /})
sed -n "${ln}p" "$fn"
于 2012-04-13T17:21:29.957 回答
0

就在 awk 中,但性能可能比 @kev 或 @MarkReed 的答案差。但是它只处理每个文件一次。需要 GNU awk

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)
        }
    }
'
于 2012-04-13T17:21:59.503 回答
0

这可能对您有用:

sed 's/^\([^,]*\),\([^,]*\).*/sed -n "\2p" \1/' file |
sort -k4,4 | 
sed ':a;$!N;s/^\(.*\)\(".*\)\n.*"\(.*\)\2/\1;\3\2/;ta;P;D' |
sh
于 2012-04-13T18:22:30.847 回答