【问题标题】:shell script(AIX) : finding a string after the matched pattern line by line in a fileshell script(AIX) : 在文件中逐行查找匹配模式之后的字符串
【发布时间】:2012-11-25 14:01:57
【问题描述】:

我在 AIX 环境中有一个日志文件,其中包含如下行

10.100.108.23 100.10.10.11 - [05/Dec/2012:09:35:27 +0000] "GET /chgs/checkprofile/checkServlet?requestType=signPart1&off=false&oquestions=true&userid=false&source=false&link=%23&country=us&language=en&origin=&displayLayer=no HTTP/1.1" 200 8904 "https://www.test.com/services/request/Home.action" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)" "PD-ERR=; rlang=nl_NL;

我需要分别从模式&country&language 之后的每一行中找到国家和语言。由于我是 shell 脚本的新手,我尝试使用 grep 和 awk 脚本来实现这一点,但没有运气。

【问题讨论】:

  • 1. whathaveyoutried.com ? (请编辑您的问题)。 2.你使用的是linux还是aix或者两者都用? (将 aix 算作 unix),除非您也安装了 GNU coreutils,否则 Aix 将需要最低公分母解决方案。
  • 请发布您目前尝试过的 grep 和 awk 脚本,否则问题可能会被关闭。

标签: linux shell unix aix


【解决方案1】:
awk -F"&" '{for(i=1;i<=NF;i++)if($i~/country/ ||$i~/language/){split($i,a,"=");printf a[2]" "}}' your_file

或者你可以使用 sed:

sed -e 's/.*country=//g;s/language=\([^\&]*\)&.*/\1/g' your_file

用于删除该 & 符号:

> sed -e 's/.*country=//g;s/&language=\([^\&]*\)&.*/ \1/g' temp
us en

你可以阅读this

【讨论】:

  • 非常感谢!!第二个给了我输出,但它们之间有一个 & 符号。我怎样才能删除它?我可以在两者之间添加下划线 (_)。
  • 您将 tegex 更改为 's/.*country=//g;s/&language=([^\&]*)&.*/ \1/g'
  • 非常感谢。你的第三个选项就像没有'&'的魅力。我想知道模式背后的逻辑。请让我知道我可以在哪里学习这些。
  • @sarathi,你假设language 紧跟country
  • 这个 awk 可能更简单:awk -F'[=&amp;? ]' '{for(i=1; i&lt;NF; i++) if ($i == "country" || $i == "language") print $(i+1)}'
【解决方案2】:

使用grep:

$ grep -Eo '(country|language)=[^&]*' file
country=us
language=en

$ grep -Po '(?<=country=|language=)[^&]*' file
us
en

#  Grep Options

-o, --only-matching       show only the part of a line matching PATTERN
-E, --extended-regexp     PATTERN is an extended regular expression (ERE)
-P, --perl-regexp         PATTERN is a Perl regular expression

使用sed

sed -E 's/.*country=([^&]*).*language=([^&]*).*/\1 \2/g' file
us en 

# Sed option

-E use extended regular expression

【讨论】:

  • 当我使用 AIX 时,那里无法识别 -o。请告诉我 o 的用法,以便我在 AIX 中找到替代方法
  • 感谢您帮助我。希望这对不使用 AIX 的人有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
  • 2014-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多