使用sed插入多行并保持它们的缩进
使用sed插入多行并保持它们的缩进
我有一些Tython函数想要插入到一个文件中。使用变量和一些\n
插入多行本身效果良好,但缩进没有保留。因为这是Python代码,这是一个大问题,代码无法正常工作。
下面是我尝试过的内容:
cat sed-insertlines.sh
#!/bin/bash read -r -d '' lines_to_insert << 'EOF' def string_cleanup(x, notwanted):\n for item in notwanted:\n x = re.sub(item, '', x)\n return x\n EOF lines_to_insert=$(echo ${lines_to_insert} ) sed -i "/import re # Regular Expression library/a $lines_to_insert" sed-insertlines.txt
但是当我最后运行cat sed-insertlines.txt
时,我得到的结果是:
#!/bin/python import re # Regular Expression library def string_cleanup(x, notwanted): for item in notwanted: x = re.sub(item, '', x) return x def string_replace(i_string, pattern, newpattern): string_corrected = re.sub(pattern, newpattern, i_string) return string_corrected
行数是对的,但缩进却消失了。
问题的出现原因:
在给定的脚本中,我们想要使用awk命令将多行文本插入到python脚本中的特定位置。然而,awk命令默认情况下会将文本视为一个单独的字符串,因此我们无法保留插入文本的缩进。
解决方法:
为了解决这个问题,我们可以使用sed命令来插入多行文本并保留缩进。下面是解决方法的步骤:
1. 将要插入的多行文本保存在一个变量中。在给定的示例中,这个变量名为 "lines_to_insert"。
2. 使用read命令将多行文本保存到变量中。在这个例子中,我们使用了"EOF"作为结束标记。
3. 使用sed命令将保存的多行文本插入到python脚本中的特定位置。在这个例子中,我们使用awk命令来执行这个操作。
4. 在awk命令中,使用"-v"选项将shell变量传递给awk。在这个例子中,我们使用"from_shell"作为变量名。
5. 在awk命令中,使用if-else语句来检查当前行是否匹配特定模式。如果匹配成功,则将插入文本与当前行一起打印输出;如果不匹配,则只打印当前行。
6. 运行脚本,输出结果。插入的多行文本将保留原来的缩进。
下面是运行脚本后的输出结果:
#!/bin/python
import re # Regular Expression library
def string_cleanup(x, notwanted):
for item in notwanted:
x = re.sub(item, '', x)
return x
def string_replace(i_string, pattern, newpattern):
string_corrected = re.sub(pattern, newpattern, i_string)
return string_corrected
注意事项:
在给定的示例中,我们已经移除了变量"lines_to_insert"中的换行符"\n",以避免输出结果中出现额外的空行。
问题出现的原因是需要在sed命令中插入多行内容并保持它们的缩进。在这个例子中,使用sed的r命令可以实现这一目标,它可以在当前循环后插入文件的内容。
解决方法是使用r命令插入文件内容。首先,将要插入的内容写入一个临时文件,例如insertfile。然后,在sed命令中使用r命令来插入这个文件的内容。最后,删除临时文件。
下面是解决问题的具体步骤:
#!/bin/bash # Write code to be inserted into 'insertfile' with proper indentation cat <<'EOF' > insertfile def string_cleanup(x, notwanted): for item in notwanted: x = re.sub(item, '', x) return x EOF # Sed with r command sed -i '/import re # Regular Expression library/r insertfile' sed-insertlines.txt # Remove temp file rm -f insertfile
最终的结果如下:
import re # Regular Expression library def string_cleanup(x, notwanted): for item in notwanted: x = re.sub(item, '', x) return x def string_replace(i_string, pattern, newpattern): string_corrected = re.sub(pattern, newpattern, i_string) return string_corrected
这种方法很好,但也有一种不需要临时文件的版本。
问题的出现原因:
在使用sed命令将多行文本插入到文件中时,我们希望保留文本的缩进格式。然而,普通的sed命令在插入多行文本时会破坏缩进格式,导致插入的文本变成一行。
解决方法:
在第一种解决方法中,我们可以将要插入的文本保存在一个shell变量中,并使用sed命令将其插入到文件中。为了保留文本的缩进格式,我们使用了全局搜索和替换的语法,在插入文本时插入了反斜杠和换行符。
在第二种解决方法中,我们使用了mapfile命令将文本的每一行保存到一个数组中,并使用printf命令将数组中的文本插入到文件中。同样地,为了保留文本的缩进格式,我们在插入文本时插入了反斜杠和换行符。
最后,第三种解决方法使用了sed的r命令和进程替换,以避免使用临时文件。这种方法可以将文本插入到文件中,并保留文本的缩进格式。
以上是关于如何在使用sed命令插入多行文本时保留缩进格式的解决方法。根据不同的需求,我们可以选择不同的方法来解决这个问题。