[英]How to use awk/sed to replace data in a specific column in certain rows only
我有一個以空格分隔的文本文件,其中大部分行如下所示:
--- 23:123456_A_B 123456 A B [and ~600K more columns after that]
但是,有些行的前 5 列如下所示:
23 . 234567 C D
任何人都可以建議將第一列從23
更改為---
並將第二列從.
到23:234567_C_D
(使用前五列的數據),同時保持其他列不變,但僅限於以23
開頭的那些行?
假設字段分隔符只是一個空格,
sed -r 's/^23 \. ([^ ]+) ([^ ]+) ([^ ]+)/--- 23:\1_\2_\3 \1 \2 \3/' file
使用 awk 更具可讀性
awk '$1 == 23 && $2 == "." {$1 = "---"; $2 = "23:" $3 "_" $4 "_" $5} 1' file
使用 sed,您可以使用-i
選項就地保存更改。
使用 awk,您可能必須顯式寫入臨時文件:
tmp=$(mktemp)
awk '....' file > "$tmp" && mv "$tmp" file
這是你想要的嗎?
$ cat file
--- 23:123456_A_B 123456 A B [and ~600K more columns after that]
23 . 234567 C D
$ awk '$1==23 { $2=$1":"$3"_"$4"_"$5; $1="---" }1' file
--- 23:123456_A_B 123456 A B [and ~600K more columns after that]
--- 23:234567_C_D 234567 C D
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.