我有一些文本文件,我希望能够在任何文件中的任意行上移或下移一行(文件开头或结尾的行将保留在原处)。我有一些有效的代码,但似乎有些杂乱无章,而且我不相信我涵盖了所有的极端情况,因此我想知道是否有某种工具或范例可以做到更好(例如,更容易理解代码(对于其他读者或我在6个月内),更易于调试,更易于维护;“更有效”并不是很重要)。
move_up() {
# fetch line with head -<line number> | tail -1
# insert that one line higher
# delete the old line
sed -i -e "$((line_number-1))i$(head -$line_number $file | tail -1)" -e "${line_number}d" "$file"
}
move_down() {
file_length=$(wc -l < "$file")
if [[ "$line_number" -ge $((file_length - 1)) ]]; then
# sed can't insert past the end of the file, so append the line
# then delete the old line
echo $(head -$line_number "$file" | tail -1) >> "$file"
sed -i "${line_number}d" "$file"
else
# get the line, and insert it after the next line, and delete the original
sed -i -e "$((line_number+2))i$(head -$line_number $file | tail -1)" -e "${line_number}d" "$file"
fi
}
我可以对这些函数内部或外部的输入进行错误检查,但是如果错误输入(如非整数,不存在的文件或行号大于文件长度的输入)得到了合理处理,则可以加分。
我希望它在现代Debian / Ubuntu系统上的Bash脚本中运行。我并不总是具有root用户访问权限,但可以期望安装“标准”工具(例如共享Web服务器),并且如果我可以证明请求的合理性,也许可以请求安装其他工具(尽管更少的外部依赖关系总会更好)。
例子:
$ cat b
1
2
3
4
$ file=b line_number=3 move_up
$ cat b
1
3
2
4
$ file=b line_number=3 move_down
$ cat b
1
3
4
2
$
与Archemar的建议类似,您可以使用以下脚本编写脚本ed
:
printf %s\\n ${linenr}m${addr} w q | ed -s infile
IE
linenr # is the line number
m # command that moves the line
addr=$(( linenr + 1 )) # if you move the line down
addr=$(( linenr - 2 )) # if you move the line up
w # write changes to file
q # quit editor
例如,移动行号。21
一排:
printf %s\\n 21m19 w q | ed -s infile
移动行号 21
向下一行:
printf %s\\n 21m22 w q | ed -s infile
但是,由于您只需要向上或向下移动某一行一行,因此您也可以说您实际上想交换两行连续的行。见面sed
:
sed -i -n 'addr{h;n;G};p' infile
IE
addr=${linenr} # if you move the line down
addr=$(( linenr - 1 )) # if you move the line up
h # replace content of the hold buffer with a copy of the pattern space
n # read a new line replacing the current line in the pattern space
G # append the content of the hold buffer to the pattern space
p # print the entire pattern space
例如,移动行号。21
一排:
sed -i -n '20{h;n;G};p' infile
移动行号 21
向下一行:
sed -i -n '21{h;n;G};p' infile
我在gnu sed
上面使用了语法。如果要考虑可移植性:
sed -n 'addr{
h
n
G
}
p' infile
除此之外,通常检查:文件是否存在并且可写;file_length > 2
; line_no. > 1
; line_no. < file_length
;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句