感谢您抽出宝贵时间来研究我的问题。我试图使用awk和sed相对较新,因为我正在尝试编写一行中的特定字符串的脚本搜索,然后打印出具有特定字符串的特定格式的文本
我的文件看起来像这样
search_string1 cat mouse fish
search_string2 cat mouse fish
notmysearchstring cat mouse fish
search_string3 cat mouse fish
我想要的是能够创建一个新文件,以便出现一个特定的字符串让我们调用“dog”:
search_string1 cat dog dog
search_string1 dog mouse dog
search_string1 dog dog fish
search_string2 cat dog dog
search_string2 dog mouse dog
search_string2 dog dog fish
search_string3 cat dog dog
search_string3 dog mouse dog
search_string3 dog dog fish
我尝试过使用awk和sed但是函数的字符串部分的格式化和插入很难理解。
感谢您的时间:)
答案 0 :(得分:0)
您可以使用awk执行此操作:
$ awk -v v="dog" \
'!/notmysearchstring/{ # Avoid non wanted pattern
l=$0 # Store the current line
split($0,a) # Get all line fields into an array
for(i=2;i<=NF;i++){ # Loop through the fields (avoid the 1st one)
for(j=2;j<=NF;j++){ # Loop through the fields (avoid the 1st one)
$j=v # Set all elements to the wanted string
};
$i=a[i] # Override with the current field
print # Display the result
$0=l # Restore the line
}
}' file
search_string1 cat dog dog
search_string1 dog mouse dog
search_string1 dog dog fish
search_string2 cat dog dog
search_string2 dog mouse dog
search_string2 dog dog fish
search_string3 cat dog dog
search_string3 dog mouse dog
search_string3 dog dog fish