如何使文件中的数据有序?
how to make the data in a file inorder?
我有一个testfile.txt如下
/path/ 345 firstline
/path2/ 346 second line
/path3/ 347 third line having spaces
/path4/ 3456 fourthline
现在我想做成下面这样
/path/,345,firstline
/path2/,346,second line
/path3/,347,third line having spaces
/path4/,3456,fourthline
根据上面的输出,数据应该由 3 列组成,所有用 commas.There 分隔的列可能是输入 file.Example、[=13= 中列之间的一个或多个空格]
/path/ and 3456
也可以用 2 个制表符分隔。第三列按原样包含空格。
谁能帮我解决这个问题?
可以使用sed
命令来实现:
我试过了,它对我有用:
sed 's/[ \t]\+/,/' testfile.txt | sed 's/[ \t]\+/,/'
它仅替换文件中空格或制表符的第一个和第二个实例。
Update
sed
(流编辑器)使用命令进行编辑。第一个参数 's/[ \t]\+/,/'
是用于将一个表达式替换为另一个的命令。进一步拆分此命令:
Syntax: s/expression1/expression2/
s - substitute
/ - expression separator
[ \t]\+ - (expression1) this is the expression to find and replace (This regular expression matches one or more space or tab characters)
, - (expression2) this is what you want to replace the first expression with
当上面的命令是 运行 时,在每一行中替换表达式的第一个实例。因为您还需要替换第二个定界符,所以我将第一个 sed
命令的输出通过管道传递给另一个类似的命令。这用 ,
.
替换了第二个分隔符
希望对您有所帮助!
tr -s ' ' <data |sed -e 's/\s/,/' -e 's/\s/,/'
/path/,345,firstline
/path2/,346,second line
/path3/,347,third line having spaces
/path4/,3456,fourthline
这不是执行此操作的最佳方法,但它会生成所需的输出。
我有一个testfile.txt如下
/path/ 345 firstline
/path2/ 346 second line
/path3/ 347 third line having spaces
/path4/ 3456 fourthline
现在我想做成下面这样
/path/,345,firstline
/path2/,346,second line
/path3/,347,third line having spaces
/path4/,3456,fourthline
根据上面的输出,数据应该由 3 列组成,所有用 commas.There 分隔的列可能是输入 file.Example、[=13= 中列之间的一个或多个空格]
/path/ and 3456
也可以用 2 个制表符分隔。第三列按原样包含空格。
谁能帮我解决这个问题?
可以使用sed
命令来实现:
我试过了,它对我有用:
sed 's/[ \t]\+/,/' testfile.txt | sed 's/[ \t]\+/,/'
它仅替换文件中空格或制表符的第一个和第二个实例。
Update
sed
(流编辑器)使用命令进行编辑。第一个参数 's/[ \t]\+/,/'
是用于将一个表达式替换为另一个的命令。进一步拆分此命令:
Syntax: s/expression1/expression2/
s - substitute
/ - expression separator
[ \t]\+ - (expression1) this is the expression to find and replace (This regular expression matches one or more space or tab characters)
, - (expression2) this is what you want to replace the first expression with
当上面的命令是 运行 时,在每一行中替换表达式的第一个实例。因为您还需要替换第二个定界符,所以我将第一个 sed
命令的输出通过管道传递给另一个类似的命令。这用 ,
.
希望对您有所帮助!
tr -s ' ' <data |sed -e 's/\s/,/' -e 's/\s/,/'
/path/,345,firstline
/path2/,346,second line
/path3/,347,third line having spaces
/path4/,3456,fourthline
这不是执行此操作的最佳方法,但它会生成所需的输出。