-4

I have a file name test, it contains a String James Bond 007, and i want to print only James Bond. I tried the following commands:

$ strings -n 2 test
$ sed -n '/James/,/Bond/p' test
$ awk '{print substr($1,10)}' test
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • What is the general criteria for what you want to print? The first two words, the first 10 characters? – Barmar May 15 '19 at 21:12
  • either of them will do but i would like to know both them :) – Ben Koren Kruiger May 15 '19 at 21:13
  • echo James Bond 007 | awk '{print $1" "$2}' ; echo James Bond 007 | cut -d " " -f1,2 – py9 May 15 '19 at 21:18
  • Possible duplicate of [Extract substring in Bash](https://stackoverflow.com/q/428109/608639), [How to retrieve the first n characters of a variable in Bash?](https://stackoverflow.com/q/14992658/608639), etc. – jww May 15 '19 at 21:31

1 Answers1

2

To print the first two words, you can use awk:

awk '{print $1, $2}' test

To print the first ten characters, you can put the file contents in a variable, then use the bash substring operation:

contents=$(cat test)
echo "${contents:0:10}"

Or in awk:

awk '{print substr($0, 1, 10)}' test

Notice that $0 means the whole line, and you have to give both a starting index and length to substr(). Indexes in awk start at 1 rather than 0.

In sed, /James/,/Bond/ is a line range expression; it processes all the lines starting from a line containing James until a line containing Bond. It doesn't process just part of the lines.

Barmar
  • 741,623
  • 53
  • 500
  • 612