我的脚本读取输入文件,例如。 myscript < testfile
并将任何只有一个单词的行复制到新文件中。
但是,我试图写一个通过循环增加的某个行号,而且文本变量也会改变,但是到目前为止我所拥有的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时,没有写入任何内容。
感谢。
答案 0 :(得分:1)
有三件事导致你的剧本无法运作
1您没有从输入文件中读入
您的while / read
声明的格式应为
while read line;do
...
done < testfile
2您正在递增$line_num
但使用$line_count
3您的sed
声明引用了不存在的行号
我相信此脚本可以满足您的需求 - 但testfile
的行数少于printf
语句中新行的限制
(我无法想到用一堆线创建新文件的更好方法)
#!/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
答案 1 :(得分:0)
保留一个字线,其余部分变空。
$ sed -e '/^[[:graph:]]\+$/! s/.*//' <<EOF
word
word word
0123456789
0123456789 0123456789
xxx
xx xx xx
xx xx xx
yyyyyyyy
EOF
word
0123456789
xxx
yyyyyyyy