我正在尝试在匹配模式时在行上方插入空行。我们有一个grep语句,它将找到该行并将行号存储在变量中。
在这个例子中,我想在第1行({1}}行上方插入一个空行,然后在第3行上方插入一行文本happy
。
这可以使用sed命令正常工作但是我想用sad
替换variable
语句中的行号,这就是失败的地方。让我继续前进并展示一个例子
我已创建以显示我遇到的问题。
这是我们的sed命令,在没有变量的情况下使用它时可以正常工作:
sed
这是我们的文件名:sed '1i\\' test # insert blank line at top of file:
,有3行:
test
我们的Line1=happy
Line2=mad
Line3=sad
语句有两个变量:
sed
以下是我们希望1: this has the line of happy - which is 1.
2. this has the line of sad - which is 3.
声明使用的变量:
sed
显示h=$(grep -n happy test | cut -d : -f 1)
s=$(grep -n sad test | cut -d : -f 1)
和h
变量似乎有效:
s
显示我们的user@host:~$ echo $h
1
user@host:~$ echo $s
3
语句可以正常输出文件开头的空白行 - 即第1行和第1行。然后也是第3行。
sed
现在我们继续使用命令替换变量sed '1i\\' test # we test that it outputs a blank line on the top of the file first - without our variable:
user@host:~$ sed '1i\\' test
# here is our blank line.
happy
mad
sad
user@host:~$ sed '3i\\' test
happy
mad
# here is our blank line for line 3.
sad
和h
中定义的变量对其进行测试,以便我们可以尝试执行与上面相同的操作。
这是它不起作用的地方 - 我不会测试两个变量,因为它不适用于第一个变量。我尝试过不同的语法,我已经大量研究但无法使用s
来处理变量。
sed
我尝试过其他几种形式的引号/标记等,试图让它发挥作用。我仔细阅读了堆栈溢出,发现如果使用变量,我应该在命令周围使用引号。
我已经给出了一个评论,可以在我的变量周围使用{},但是在执行此操作时,它不会像使用真实文本那样输出上面的行:
sed "$si\\" test # try to insert the blank line with the variable at top of file
user@host:~$ sed '$hi\\' test # we test that it outputs a blank line on the top of the file first - with our variable with ticks ' ':
sed: -e expression #1, char 3: extra characters after command
user@host:~$ sed "$hi\\" test # we test that it outputs a blank line on the top of the file first - with our variable with quotes " " :
sed: -e expression #1, char 1: unterminated address regex
user@host:~$ sed "'$hi\\'" test # we test that it outputs a blank line on the top of the file first - with our variable with quotes/ticks "' '" :
sed: -e expression #1, char 1: unknown command: `''
答案 0 :(得分:1)
您的第一个问题是"$gi"
正在寻找不存在的变量$gi
。为了避免这种情况,您必须在变量名称周围加上大括号,如"${g}i"
中所示,或者在变量名和sed命令之间加一个空格,如"$g i"
中所示。
然后,因为你的测试工作使用单引号,所以双字斜杠按字面解释。在双引号中,必须转义反斜杠,导致
sed "${h}i\\\\" test
最后,这似乎过于复杂了。要在包含模式的行之前插入空行,您可以使用它(例如happy
):
sed '/happy/s/^/\n/' test
这"取代"如果该行与happy
匹配,则为换行符的开头。
请注意,插入这样的换行符并不适用于每个sed;对于macOS sed,你可以使用像
这样的东西sed 'happy/s/^/'$'\n''/' test
答案 1 :(得分:1)
使用grep
获取行号,以便将其传递给sed
,这是一个反模式。您想要在sed
中进行所有处理。
sed -e '/happy/i\\' -e '/sad/i\\' file
如果两种情况下的操作确实相同,则可以将其与单个正则表达式混淆。
sed '/\(happy\|sad\)/i\\' file
(精确的语法会因sed
种方言而异,但您明白了。如果sed
有-r
或-E
,您可以避免使用反斜杠。)
答案 2 :(得分:0)
这应该完美。我在Ubuntu上测试它没有任何问题。
number=3
sed $number'i\\' test.txt
问候!