簡體   English   中英

如何將由不同分隔符分隔的兩個不同列提取到同一行中

[英]How to extract two different columns separated by different delimiters into the same line

我在unix txt文件中有以下數據集:

/this/is/a/directory_name/which/i/want:listen= tcp://someurl
/this/is/a/another_directory_name/which/i/want:listen= tcp://someotherurl

基本上打算輸出的是:

directory_name <whitespace> tcp://someurl
another_directory_name <whitespace> tcp://someotherurl

下面是我正在嘗試但只獲取url或者directoryname的命令

cat the_file.txt|awk -F '/' '{print $5}'
cat the_file.txt|awk -F '=' '{print $2}'

有沒有辦法同時獲得上述兩個命令並獲得同一行的輸出? 非常感興趣

只需保留第一個命令並對第二個命令進行調整:基於= 拆分全文並打印第二個結果字段:

$ awk -F'/' '{split($0, a,"="); print $5, a[2]}' file
directory_name  tcp://someurl
another_directory_name  tcp://someotherurl

如果有很多= s,那么最后一個:

$ awk -F'/' '{n=split($0, a,"="); print $5, a[n]}' file
directory_name  tcp://someurl
another_directory_name  tcp://someotherurl

sed

$ sed -E 's|^([^/]*/){4}([^/]+).*=|\2|' ip.txt 
directory_name tcp://someurl
another_directory_name tcp://someotherurl
  • -E使用ERE,某些版本需要-r代替
  • ^([^/]*/){4}與所需字段之前/之前匹配
  • ([^/]+)必填字段
  • .*= upto last =在行中
  • \\2替換為必填字段,在給定樣本中tcp前有空格,如果不能保證,請使用s|^([^/]*/){4}([^/]+).*= *|\\2 |
$ awk '{split($1,d,"/"); print d[5], $2}' file
directory_name tcp://someurl
another_directory_name tcp://someotherurl

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM