![字符串的多重串联,无需写入中间文件](https://linux22.com/image/131181/%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%E5%A4%9A%E9%87%8D%E4%B8%B2%E8%81%94%EF%BC%8C%E6%97%A0%E9%9C%80%E5%86%99%E5%85%A5%E4%B8%AD%E9%97%B4%E6%96%87%E4%BB%B6.png)
我想提取一些文件的一部分并将它们连接到另一个文件中,但不编写中间文件。
例如:
$ cat textExample.txt
Much I marvelled this ungainly fowl to hear discourse so plainly,
Though its answer little meaning- little relevancy bore;
For we cannot help agreeing that no living human being
Ever yet was blessed with seeing bird above his chamber door-
Bird or beast upon the sculptured bust above his chamber door,
With such name as "Nevermore."
$ cat textExample.txt | tr -d "\n" | awk 'NR==1' | awk '{print substr($0, 8, 9)}'
marvelled
$ cat textExample.txt | tr -d "\n" | awk 'NR==1' | awk '{print substr($0, 77, 6)}'
answer
$ cat textExample.txt | tr -d "\n" | awk 'NR==1' | awk '{print substr($0, 189, 7)}'
blessed
为了将句子连接在一起,可以编写一个文件:
$ cat textExample.txt | tr -d "\n" | awk 'NR==1' | awk '{print substr($0, 8, 9)}'| tr "\n" " " > intermediate.txt
$ cat textExample.txt | tr -d "\n" | awk 'NR==1' | awk '{print substr($0, 77, 6)}' | tr "\n" " " >> intermediate.txt
$ cat textExample.txt | tr -d "\n" | awk 'NR==1' | awk '{print substr($0, 189, 7)}' >> intermediate.txt
$ cat intermediate.txt
marvelled answer blessed
或者可以使用多个 awk 命令(尽管我无法删除换行符):
$ cat textExample.txt | tr -d "\n" | awk 'NR==1' | awk '{print substr($0, 8, 9)}; {print substr($0, 77, 6)}; {print substr($0, 189, 7)}'
marvelled
answer
blessed
我想知道是否cat
可以直接使用将不同的单词连接在一起而不依赖中间文件,例如:
$ cat {first word} | cat {second word} | cat {third word}
first second third
谢谢
答案1
如果我正确理解你的话,这对我有用:
cat textExample.txt | tr -d "\n" | awk '{print substr($0, 8, 9) " " substr($0, 77, 6) " " substr($0, 189, 7)}'
答案2
我不明白你的意图。
但请尝试:
... | tr -d '\n' |
awk '{printf "%s %s %s\n", substr($0, 8, 9),substr($0, 77, 6),substr($0, 189, 7)}'
给出你的输入
tr -d '\n' < se | awk '{printf "%s %s %s\n", substr($0, 8, 9),substr($0, 77, 6),substr($0, 189, 7)}'
marvelled answer blessed
- 看一下
printf
,默认情况下不以换行符结尾(与 相反print
)
另请注意,您可以使用子shell
( cmd1 arg 1
cmd2 arg for 2
cmd 3 ) > result
这会将cmd
s的输出放入result
.
答案3
用bash
cat extract_words.sh
#!/bin/bash
concat=" "
min=$(($6+$7))
while read line
do
concat="$concat$line"
if test "${#concat}" -ge "$min" ; then
break
fi
done < "$1"
echo "${concat:$2:$3}" "${concat:$4:$5}" "${concat:$6:$7}"
你就这样称呼它
./extract_words.sh "textExample.txt" 8 9 77 6 189 7