字符串的多重串联,无需写入中间文件

字符串的多重串联,无需写入中间文件

我想提取一些文件的一部分并将它们连接到另一个文件中,但不编写中间文件。

例如:

$ 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

这会将cmds的输出放入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

相关内容