如何在第 n 行文件的中间插入文本
How to insert a text in middle of nth line of file
我想在文件的第 n 行之间插入一个管道符号。就像 diff 命令输出中的那个。
不想使用VI编辑器。
例如,所需行是文件的第 2 行:
cat filename
Hi Hi
Hello Hello
This This
is Is
it it
期望的输出:
cat 文件名
Hi Hi
Hello | Hello
This This
is Is
it it
你基本上不能通过在一行中插入一个字符来修改一些文本文件。您需要读取它的所有内容,在内存中修改该内容,然后写入新内容。
您可能对 GNU ed 感兴趣,它可以以编程方式(在某些脚本中)编辑文件。
您可以使用 awk
(或任何其他过滤器)并将其输出重定向到某个临时文件,然后将该临时文件重命名为原始文件。
sed '
# select 2nd line
/2/ {
# keep original in memory
G;h
:divide
# cycle by taking the 2 char at the egde of string (still string end by the \n here) and copy only first to other part of the separator (\n)
s/\(.\)\(.*\)\(.\)\(\n.*\)//
# still possible, do it again
t divide
# add last single char if any and remove separator
s/\(.*\)\n\(.*\)//
# add original string (with a new line between)
G
# take first half string and end of second string, and place a pipe in the middle in place of other char
s/\(.*\)\n\(.*\)/|/
}' YourFile
- posix sed,所以
--POSIX
GNU sed
- 选择解释
为了您自己的理智,请使用 awk:
$ awk 'NR==2{mid=length([=10=])/2; [=10=]=substr([=10=],1,mid) "|" substr([=10=],mid+1)} 1' file
Hi Hi
Hello | Hello
This This
is Is
it it
要修改原始文件,您可以添加 > tmp && mv tmp file
或使用 -i inplace
(如果您有 GNU awk)。
我想在文件的第 n 行之间插入一个管道符号。就像 diff 命令输出中的那个。
不想使用VI编辑器。
例如,所需行是文件的第 2 行:
cat filename
Hi Hi
Hello Hello
This This
is Is
it it
期望的输出:
cat 文件名
Hi Hi
Hello | Hello
This This
is Is
it it
你基本上不能通过在一行中插入一个字符来修改一些文本文件。您需要读取它的所有内容,在内存中修改该内容,然后写入新内容。
您可能对 GNU ed 感兴趣,它可以以编程方式(在某些脚本中)编辑文件。
您可以使用 awk
(或任何其他过滤器)并将其输出重定向到某个临时文件,然后将该临时文件重命名为原始文件。
sed '
# select 2nd line
/2/ {
# keep original in memory
G;h
:divide
# cycle by taking the 2 char at the egde of string (still string end by the \n here) and copy only first to other part of the separator (\n)
s/\(.\)\(.*\)\(.\)\(\n.*\)//
# still possible, do it again
t divide
# add last single char if any and remove separator
s/\(.*\)\n\(.*\)//
# add original string (with a new line between)
G
# take first half string and end of second string, and place a pipe in the middle in place of other char
s/\(.*\)\n\(.*\)/|/
}' YourFile
- posix sed,所以
--POSIX
GNU sed - 选择解释
为了您自己的理智,请使用 awk:
$ awk 'NR==2{mid=length([=10=])/2; [=10=]=substr([=10=],1,mid) "|" substr([=10=],mid+1)} 1' file
Hi Hi
Hello | Hello
This This
is Is
it it
要修改原始文件,您可以添加 > tmp && mv tmp file
或使用 -i inplace
(如果您有 GNU awk)。