用bash中的另一个字符串替换结束括号
我想用另一个字符串替换最后3行。。使用用bash中的另一个字符串替换结束括号,bash,sed,tr,Bash,Sed,Tr,我想用另一个字符串替换最后3行。。使用sed、tr或其他bash解决方案 给定文件: { [ { text text text text text text text text text } ], [ { text text text text text text text text text } ] } 预期结果: { [ { text text
sed
、tr
或其他bash
解决方案
给定文件:
{
[
{
text text text
text text text
text text text
}
],
[
{
text text text
text text text
text text text
}
]
}
预期结果:
{
[
{
text text text
text text text
text text text
}
],
[
{
text text text
text text text
text text text
bar
我用sed
sed -i '' 's/\}\s+\]\s+\}/bar/g' foobar.hcl
用tr
tr -s 's/\}[:blank:]\][:blank:]\}/bar/g' <foobar.hcl
tr-s的/\}[:blank:][\][:blank:][\}/bar/g'这可能适合您(GNU-sed):
打开一个三行窗口并进行模式匹配。使用perl
可以使用-0777
选项以单个字符串的形式读取整个输入。如果输入足够大,可用内存不足,则不适用
#这将替换结尾处所有剩余的空白
#只有一条换行
perl-0777-pe's/\}\s+]\s+\}\s*\z/bar\n/'foobar.hcl
#这将保留所有剩余的空白(如果有的话)
perl-0777-pe's/\}\s+]\s+\}(?=\s*\z)/bar/'foobar.hcl
一旦它工作,您就可以使用perl-i-0777…
进行就地编辑。使用数组-假设“文本”具有一些实际的非空格、非标点字符
mapfile x < file # throw into an array
c=${#x[@]} # count the lines
let c-- # point c at last index
until [[ "${x[-1]}" =~ [^[:space:][:punct:]] ]] # while last line has no data
do let c-- # decrement the last line pointer
x=( "${x[@]:0:$c}" ) # reassign array without last line
done
x+=( bar ) # add the desired string
echo "${x[@]}" > file # write file without unwanted lines
mapfilex文件#写入文件时没有不需要的行
允许任意数量的空行&c。即使是}]}
等等,只要它与数据不在同一行。你试过什么吗?如果是,请与我们分享。我调整了描述并添加了我尝试的内容请更新问题以显示所需的内容result@markp-fuso donewill您要替换的3行始终是文件的最后3行吗?这三行是否也会出现在文件中的其他地方?这三条线会多次出现吗?真是太棒了!我不能投票,因为我没有足够的声誉谢谢!
mapfile x < file # throw into an array
c=${#x[@]} # count the lines
let c-- # point c at last index
until [[ "${x[-1]}" =~ [^[:space:][:punct:]] ]] # while last line has no data
do let c-- # decrement the last line pointer
x=( "${x[@]:0:$c}" ) # reassign array without last line
done
x+=( bar ) # add the desired string
echo "${x[@]}" > file # write file without unwanted lines