我用的是bash。我需要处理一个字符串,但这是相当棘手的。
这个文件包含这样的文件列表(只是一个例子):
apple.o
orange.bin
banana.o
kiwi.o我希望将该文件的内容转换为如下所示的字符串:
apple.o+orange.bin+banana.o+kiwi.o我想用\n分隔文件的内容,并将+放在元素中。
这似乎是个愚蠢的问题。但是我是新手,对此我没有太多的经验。我真的不知道这事。
但是,我认为如果在for循环中正确使用if语句是可能的。
简单的伪代码(可能有一些问题):
for line in 0..number_of_line:
if line notequal number_of_line:
put content[line] with "+" into result
else:
put content[line] into result我很感谢你的帮助。谢谢。
发布于 2021-03-06 11:23:48
纯bash
str=$(< file) # Slurp the file into the variable `str`
str=${str%$'\n'} # Remove the last character if it is a newline
str=${str//$'\n'/+} # Replace all newlines with `+`
echo "$str" # Print the variable to see its contents发布于 2021-03-06 11:40:52
一个以文件名作为参数并返回已连接文件的bash函数:
slurpfile() {
local IFS=+
mapfile -t lines < "$1"
printf "%s" "${lines[*]}"
}示例用法:
combined=$(slurpfile input.txt)
printf "%s\n" "$combined"它只是将文件读入一个数组中,每个元素一行,然后将它们与正确的元素之间的IFS分隔符连接起来。
发布于 2021-03-06 11:42:25
通常,我使用awk来解析文本,因为它更快、更可移植。
在一行中打印所有行,并在每行中添加+:
awk 'BEGIN{ORS="+"}1' file.txt要删除最后一次出现的+,请执行以下操作:
sed 's/\(.*\)+/\1/'单行版本:
awk 'BEGIN{ORS="+"}1' file.txt | sed 's/\(.*\)+/\1/'https://stackoverflow.com/questions/66505027
复制相似问题