Linux 在bash中使用sed写入变量指定的行号
我的脚本读取一个输入文件,例如Linux 在bash中使用sed写入变量指定的行号,linux,bash,sed,Linux,Bash,Sed,我的脚本读取一个输入文件,例如myscriptnewfile.txt?好的,我添加了整个脚本。我还指一些示例输入和所需的输出。sed-i选项用于替换现有文件,而不是新文件谢谢。不需要使用“\n”,但由于创建文件后只需要一个“\n”,因此sed将写入该文件,并始终在文件末尾留下一个空行。 #!/bin/bash line_num=1 line_count=0 word_count=0 printf "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" > newfile.tx
myscript
,并将只有一个单词的任何行复制到一个新文件中
然而,我试图写入一个通过循环增加的特定行号,文本变量也会发生变化,但是到目前为止,我的sed代码没有向新文件提供任何输出
#!/bin/bash
line_num=1
line_count=0
word_count=0
text_in_line=""
while read line;do
text_in_line="$line"
echo "line $line_num: $(echo $text_in_line | wc -w)"
word_count=$(echo $text_in_line | wc -w)
if [ $word_count = 1 ]; then
echo "word count is: $word_count"
((line_count++))
sed -i "${line_count}i${text_in_line}" newfile.txt
fi
((line_num++))
done
有人能告诉我正确的密码吗。但是,当我打开newfile.txt时,它没有给出任何错误,没有写入任何内容
谢谢。保留一行字,其余的变为空
$ sed -e '/^[[:graph:]]\+$/! s/.*//' <<EOF
word
word word
0123456789
0123456789 0123456789
xxx
xx xx xx
xx xx xx
yyyyyyyy
EOF
有三个因素导致脚本无法运行 1您没有从输入文件读入 您的
while/read
语句应为
while read line;do
...
done < testfile
你能提供一个吗?比如
cat-n oldfile.txt>newfile.txt
?好的,我添加了整个脚本。我还指一些示例输入和所需的输出。sed-i
选项用于替换现有文件,而不是新文件谢谢。不需要使用“\n”,但由于创建文件后只需要一个“\n”,因此sed将写入该文件,并始终在文件末尾留下一个空行。
#!/bin/bash
line_num=1
line_count=0
word_count=0
printf "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" > newfile.txt
while read line;do
text_in_line="$line"
# echo "line $line_num: $(echo $text_in_line | wc -w)"
word_count=$(echo $text_in_line | wc -w)
echo "line count of subject is: $line_count"
if [ $word_count = 1 ]; then
echo "word count is: $word_count"
sed -i "${line_count}i${text_in_line}" newfile.txt
fi
(( line_count++ ))
done < testfile