访问字符串的特定部分是一行

时间:2013-09-13 11:55:45

标签: bash shell sed grep cut

我的文件内容:file.conf是

sm key mappings
sm_key_7_value_0="/www/cgi-bin/scripts/app_web_mood_control.sh Global masteron;echo hello"
sm_key_7_value_1="/www/cgi-bin/scripts/app_web_mood_control.sh Global masteroff"
sm_key_8_value_0="/www/cgi-bin/scripts/app_web_mood_control.sh Global green"
sm_key_8_value_1="/www/cgi-bin/scripts/app_web_mood_control.sh Global away"
sm_key_9_value_0="/www/cgi-bin/scripts/app_usr_core_sendPulse.sh CR_D601 C1_OPN"
sm_key_9_value_1="/www/cgi-bin/scripts/app_usr_core_sendPulse.sh CR_D601 C1_CLS"
sm_key_A_value_0="/www/cgi-bin/scripts/app_oasis_irControl.sh IR_D03 AC_ON_"
sm_key_A_value_1="/www/cgi-bin/scripts/app_oasis_irControl.sh IR_D03 AC_OFF"
sm_key_B_value_0="/www/cgi-bin/scripts/app_usr_core_sendInstruction.sh CR_D601 OP_01N"
sm_key_B_value_1="/www/cgi-bin/scripts/app_usr_core_sendInstruction.sh CR_D601 OP_01F"
sm_key_C_value_0="/www/cgi-bin/scripts/app_usr_core_sendInstruction.sh CR_D601 OP_02N"
sm_key_C_value_1="echo 123 && $(sleep 5) && $(echo hello)"

我用过grep

 grep "/www/cgi-bin/scripts/app_web_mood_control.sh" file.conf 

grep的输出是

sm_key_7_value_0="/www/cgi-bin/scripts/app_web_mood_control.sh Global masteron;echo hello"
sm_key_7_value_1="/www/cgi-bin/scripts/app_web_mood_control.sh Global masteroff"
sm_key_8_value_0="/www/cgi-bin/scripts/app_web_mood_control.sh Global green"
sm_key_8_value_1="/www/cgi-bin/scripts/app_web_mood_control.sh Global away"

在这个grep的o / p中,我需要访问global masteron Global masteroff Global green Global away并将其放入变量中。目标是我想访问control.sh之后的任何内容并将其存储在变量中如何实现。

4 个答案:

答案 0 :(得分:1)

让你入门的东西:

$ awk -F'[ ;"]' -f g.awk your_input
Global masteron
Global masteroff
Global green
Global away

,其中

$ cat g.awk
/Global/ {
    print $3, $4
}

变量:

$ a=$(awk -F'[ ;"]' -f g.awk your_input)

$ echo $a
Global masteron Global masteroff Global green Global away

答案 1 :(得分:0)

var=$(grep -Po '(?<=/www/cgi-bin/scripts/app_web_mood_control\.sh )[^;"]*' file.conf)

试验:

kent$  a=$(grep -Po '(?<=/www/cgi-bin/scripts/app_web_mood_control\.sh )[^;"]*' f)

kent$  echo $a
Global masteron
Global masteroff
Global green
Global away

答案 2 :(得分:0)

您可以使用readarraysed

#!/bin/bash

FILE='file.conf'

# Get values.
readarray -t MATCHES < <(sed -n '/app_web_mood_control.sh/{ s|.*app_web_mood_control.sh ||; s|;.*$||; s|\"||; p; }' "$FILE")

# Demonstrate the values.
for A in "${MATCHES[@]}"; do
    echo "$A"
done

示例输出:

Global masteron
Global masteroff
Global green
Global away

数组MATCHES中保存的所有值都从索引0开始,因此您可以通过${MATCHES[0]}${MATCHES[1]}等访问它们。

答案 3 :(得分:0)

\K中使用grep

readarray -t found < <( grep -P -o '/www/cgi-bin/scripts/app_web_mood_control.sh \K[^;"]*' file.conf)

for curFound in "${found[@]}"; do
    echo "$curFound"
done

输出:

  

全球主人   全球大师级   全球绿色   全球客户