使用awk / sed从上一行复制值

时间:2019-04-25 21:12:39

标签: awk sed

有什么想法如何编写awk / sed脚本来替换特定的哨兵值或模式(在这种情况下,struct IState { int X, Y, Z, step; }; void insertIfOne(std::vector<IState>& stack, int X, int Y, int Z) { if (ptrarray[X][Y][Z] == 1) { fout << X << ";" << Y << ";" << Z << " "; ptrarray[X][Y][Z] = 0; stack.emplace_back(IState{ X, Y, Z, 0 }); } } int find_and_write_clusters(int X, int Y, int Z) { std::vector<IState> remaining; insertIfOne(remaining, X, Y, Z); while (!remaining.empty()) { auto& c = remaining.back();//current switch (c.step++) { case 0: if (c.X + 1 < k) insertIfOne(remaining, c.X + 1, c.Y, c.Z); break; case 1: if (c.Y + 1 < k) insertIfOne(remaining, c.X, c.Y + 1, c.Z); break; case 2: if (c.Z + 1 < k) insertIfOne(remaining, c.X, c.Y, c.Z + 1); break; case 3: if (c.X - 1 >= 0) insertIfOne(remaining, c.X - 1, c.Y, c.Z); break; case 4: if (c.Y - 1 >= 0) insertIfOne(remaining, c.X, c.Y - 1, c.Z); break; case 5: if (c.Z - 1 >= 0) insertIfOne(remaining, c.X, c.Y, c.Z - 1); break; default: remaining.pop_back(); } } return 0; } 来自与上一行不同的列中的值)?

例如替换上一行第一列的值中的所有PREV

PREVs

收件人:

a -> b
c -> PREV
d -> PREV

6 个答案:

答案 0 :(得分:4)

$ awk 'NR>1{$3=p} {p=$1} 1' file
a -> b
c -> a
d -> c

awk '{$3=(NR>1)?p:$3;p=$1} 1' file

答案 1 :(得分:2)

$ cat file
a -> b
c -> PREV
d -> PREV
e -> f     # watch this record
g -> PREV

要使用awk从上一行第一列的值中替换所有PREV

$ awk '$3=="PREV"{$3=prev}{prev=$1}1' file

输出:

a -> b
c -> a
d -> c
e -> f     # watch this record
g -> e

答案 2 :(得分:1)

高尔夫:

$ awk '$3=p?p:$3; {p=$1}' file

a -> b
c -> a
d -> c

说明$1==0

$ awk '$3 = length(p)? p: $3; {p=$1}' <<EOF
a -> b
c -> PREV
d -> PREV
0 -> PREV
e -> PREV
f -> PREV
EOF

a -> b
c -> a
d -> c
0 -> d
f -> e

答案 3 :(得分:1)

使用GNU sed:

sed -E '/PREV/{G;s/PREV(.*)\n(\S+).*/\2\1/};h' infile

解释:

/PREV/ {                       # if the current line matches PREV
    G                          # append hold space to pattern space
    s/PREV(.*)\n(\S+).*/\2\1/  # replace PREV with first word from appended line,
                               # drop newline and rest of appended line
}
h                              # store pattern space in hold space

或者,对可移植性进行了一些修改:

sed '/PREV/{G;s/PREV\(.*\)\n\([^[:blank:]]\{1,\}\).*/\2\1/;};h' infile

答案 4 :(得分:0)

如果您的数据位于d文件中,请尝试使用gnu sed:

sed -Ez ':s s/((\S+)\s*->[^\n]+\n[^\n]*)PREV\s*/\1\2\n/;ts' d

答案 5 :(得分:0)

对于此内容

$ cat file
a -> b
c -> PREV
d -> PREV
e -> PREV
g -> GOLD
p -> m

确保仅更换PREV前哨(其他保持原样):

$ awk 'NR>1 && /PREV/{$3=p}{p=$1} 1' file
a -> b
c -> a
d -> c
e -> d
g -> GOLD
p -> m