0

I have a text file in which may have multiple lines of text. Exactly one line of text will have the following sequence:

XMLcpLINK: ########

where the sequence of #'s can be any character or symbol.

What I need to do is read each line until I find XMLcpLINK: and save the sequence after it into a variable. Can anyone point me to sufficient UNIX references to do this?

4

6 回答 6

3

Something like

my_var=$(sed -n 's/XMLcpLINK: //p' file.txt)

should do it.

Here's a decent sed reference.

Or if you have GNU grep:

my_var=$(grep -oP '(?<=XMLcpLINK: ).*' file.txt)

Adding -m 1 to grep is a good idea ajozwik has there, it should speed it up a little.

于 2013-03-12T21:47:06.000 回答
1

grep -m 1 'XMLcpLINK' file.txt | awk '{ print $2}' - only first occurency

grep 'XMLcpLINK' file.txt | awk '{ print $2}' - all matching

于 2013-03-12T21:51:01.790 回答
1

POSIX sh

No external commands or subshells

while IFS=': ' read name value; do
    case "$name" in
        XMLcpLINK) result="$value"
    esac
done < input_file
echo "$result"
于 2013-03-12T21:57:46.507 回答
1

You got some good answers already but there is room for some improvement.

All the following print value of XMLcpLINK and then quit:

With awk:

$ awk '/^XMLcpLINK: /{print $2;exit}' file
########

With grep:

$ grep -Pom1 '(?<=^XMLcpLINK: ).*' file
########

With sed:

$ sed -n '/^XMLcpLINK: /{s/XMLcpLINK: //p;q}' file
########

Pick your favorite and use command substitution to store the result into a variable:

$ var=$(awk '/^XMLcpLINK: /{print $2;exit}' file)

$ echo $var
########
于 2013-03-13T00:33:40.710 回答
0
#!/bin/bash
VAR=$(grep "XMLcpLINK: " test.txt | awk '{ print $2 }')
echo $VAR

test.txt being the file to analyse.

于 2013-03-12T21:48:30.707 回答
0

Two ways to achieve this:

With bash and dash, the following should work, with your testfile named 'myfile.txt'

while read i; do if [ "$i" != "${i#XMLcpLink: }" ]; then variable="${i#XMLcpLink: }"; break; fi; done <myfile.txt ; echo variable == "${variable}"

For explanation of the "${var#something}" see the 'Parameter Expansion' section in the bash man page.

Or a little shorter, perhaps faster (unless the file has many nonmatching lines after the match), and if you don't mind a space prefixed to the variable, using the external grep and cut utilities:

variable="`grep -e '^XMLcpLink: ' myfile|cut -d':' -f2-`" ; echo variable == "${variable}"

There are probably many more ways, possibly some bettery ways to do it.

于 2013-03-12T22:06:59.320 回答