我有一个大约 3200 行长的以空格分隔的文件。每行包含 7 个以上的字段。
我想要做的是编辑文件,sed
以便在字段 5 中包含某个变量的每一行都将其字段 1 更改为 X。
我在想的是做这样的事情:
for variable in `cat word.list.file`
do
sed 's/line_with_$variable_in_field5/replace_field1_with_X/g' old.file > new.file
cp new.file old.file
done
Run Code Online (Sandbox Code Playgroud)
这样对吗?有没有更好的办法?
我需要帮助的是填写sed
命令或寻找替代方法来完成同样的事情。
如果能让事情变得更容易,我可以轻松地将空格分隔的文件转换为逗号分隔的文件。
如果需要澄清,请告诉我。
这可以防止多次读取每个文件。它只读取每个文件一次。
awk 'NR == FNR {a[$1]=1;next} $5 in a {$1="XYZ"} {print}' word.list.file old.file > new.file && mv new.file old.file
Run Code Online (Sandbox Code Playgroud)
解释:
# if the current record number is the same as the record number in the file
# which means "if we're reading the first file"
NR == FNR {
a[$1]=1 # put a flag in an array indexed by the contents of the first field
next # read the next line in the file and continue at the top of the script
}
# Now we're processing the second file
# if field 5 exists as an index in the array named "a" (it's a word from the first file)
$5 in a {
$1="XYZ" # replace the first field with new contents
}
# for all lines in the second file, changed or not
{
print # print them
}' \
word.list.file old.file \
> new.file && \
mv new.file old.file
Run Code Online (Sandbox Code Playgroud)
使用文件“word.list.file”和“old.file”作为输入。将输出写入“new.file”。如果整个操作没有产生错误 ( &&
),则将“new.file”重命名回“old.file”。本段中描述的部分是整个 Bash(或 shell)的唯一部分。顶部原始命令中由注释行描述的部分是一个 AWK 脚本。AWK 本身就是一种编程语言,独立于外壳。