I have a command, for example: echo "word1 word2"
. I want to put a pipe (|
) and get «word1» from the command.
echo "word1 word2" | ....
What should I put after the pipe?
asked Mar 13, 2010 at 23:09
AWK is a good option if you have to deal with trailing whitespace because it’ll take care of it for you:
echo " word1 word2 " | awk '{print $1;}' # Prints "word1"
cut won’t take care of this though:
echo " word1 word2 " | cut -f 1 -d " " # Prints nothing/whitespace
‘cut’ here prints nothing/whitespace, because the first thing before a space was another space.
answered Mar 13, 2010 at 23:37
mattbhmattbh
5,2102 gold badges27 silver badges27 bronze badges
5
There isn’t any need to use external commands. Bash itself can do the job. Assuming «word1 word2» you got from somewhere and stored in a variable, for example,
$ string="word1 word2"
$ set -- $string
$ echo $1
word1
$ echo $2
word2
Now you can assign $1
, $2
, etc. to another variable if you like.
answered Mar 13, 2010 at 23:59
ghostdog74ghostdog74
323k56 gold badges257 silver badges342 bronze badges
6
I think one efficient way is the use of Bash arrays:
array=( $string ) # Do not use quotes in order to allow word expansion
echo ${array[0]} # You can retrieve any word. Index runs from 0 to length-1
Also, you can directly read arrays in a pipe-line:
echo "word1 word2" | while read -a array; do echo "${array[0]}" ; done
answered May 3, 2015 at 10:20
IsaíasIsaías
4524 silver badges7 bronze badges
5
echo "word1 word2 word3" | { read first rest ; echo $first ; }
This has the advantage that is not using external commands and leaves the $1, $2, etc. variables intact.
answered May 20, 2014 at 2:33
John MarterJohn Marter
6917 silver badges4 bronze badges
2
Using shell parameter expansion %% *
Here is another solution using shell parameter expansion. It takes care of multiple spaces after the first word. Handling spaces in front of the first word requires one additional expansion.
string='word1 word2'
echo ${string%% *}
word1
string='word1 word2 '
echo ${string%% *}
word1
Explanation
The %%
signifies deleting the longest possible match of *
(a space followed by any number of whatever other characters) in the trailing part of string
.
answered Dec 10, 2016 at 18:41
Serge StroobandtSerge Stroobandt
27.4k8 gold badges106 silver badges99 bronze badges
You could try AWK:
echo "word1 word2" | awk '{ print $1 }'
With AWK it is really easy to pick any word you like ($1
, $2
, etc.).
answered Mar 13, 2010 at 23:21
mfloryanmfloryan
7,6674 gold badges31 silver badges44 bronze badges
If you are sure there are no leading spaces, you can use Bash parameter substitution:
$ string="word1 word2"
$ echo ${string/% */}
word1
Watch out for escaping the single space. See here for more examples of substitution patterns. If you have Bash > 3.0, you could also use regular expression matching to cope with leading spaces — see here:
$ string=" word1 word2"
$ [[ ${string} =~ *([^ ]*) ]]
$ echo ${BASH_REMATCH[1]}
word1
answered Nov 13, 2014 at 14:00
dsl101dsl101
1,71916 silver badges35 bronze badges
I wondered how several of the top answers measured up in terms of speed. I tested the following:
1 @mattbh’s
echo "..." | awk '{print $1;}'
2 @ghostdog74’s
string="..."; set -- $string; echo $1
3 @boontawee-home’s
echo "..." | { read -a array ; echo ${array[0]} ; }
and 4 @boontawee-home’s
echo "..." | { read first _ ; echo $first ; }
I measured them with Python’s timeit
in a Bash script in a zsh terminal on macOS, using a test string with 215 5-letter words. I did each measurement five times (the results were all for 100 loops, best of 3), and averaged the results:
Method Time
--------------------------------
1. awk 9.2 ms
2. set 11.6 ms (1.26 * "1")
3. read -a 11.7 ms (1.27 * "1")
4. read 13.6 ms (1.48 * "1")
answered Mar 14, 2018 at 17:49
henryhenry
4,1842 gold badges26 silver badges37 bronze badges
2
echo "word1 word2" | cut -f 1 -d " "
cut cuts the first field (-f 1
) from a list of fields delimited by the string » » (-d " "
).
answered Mar 13, 2010 at 23:11
lajuettelajuette
9971 gold badge7 silver badges18 bronze badges
2
read
is your friend:
-
If string is in a variable:
string="word1 word2" read -r first _ <<< "$string" printf '%sn' "$first"
-
If you’re working in a pipe: first case: you only want the first word of the first line:
printf '%sn' "word1 word2" "line2" | { read -r first _; printf '%sn' "$first"; }
second case: you want the first word of each line:
printf '%sn' "word1 word2" "worda wordb" | while read -r first _; do printf '%sn' "$first"; done
These work if there are leading spaces:
printf '%sn' " word1 word2" | { read -r first _; printf '%sn' "$first"; }
answered Nov 13, 2014 at 15:20
gniourf_gniourfgniourf_gniourf
44k9 gold badges92 silver badges102 bronze badges
As Perl incorporates AWK’s functionality, this can be solved with Perl too:
echo " word1 word2" | perl -lane 'print $F[0]'
answered Jan 26, 2017 at 8:15
tsschtssch
7248 silver badges25 bronze badges
1
If you don’t mind installing a new command, I would recommend choose
It has the simplest and most intuitive interface of all alternatives:
echo "word1 word2" | choose 0
answered Sep 23, 2022 at 19:56
Klas MellbournKlas Mellbourn
41.8k22 gold badges140 silver badges157 bronze badges
I was working with an embedded device which had neither Perl, AWK or Python and did it with sed instead. It supports multiple spaces before the first word (which the cut
and bash
solutions did not handle).
VARIABLE=" first_word_with_spaces_before_and_after another_word "
echo $VARIABLE | sed 's/ *([^ ]*).*/1/'
This was very useful when grepping ps
for process IDs since the other solutions here using only Bash was not able to remove the first spaces which ps
uses to align.
answered Jan 5, 2018 at 10:49
Johan BjäreholtJohan Bjäreholt
7221 gold badge12 silver badges24 bronze badges
When I echo *
I get the following output:
file1 file2 file3 ...
What I want is to pick out the first word. How can I proceed?
asked Feb 24, 2013 at 11:55
vdegennevdegenne
1,6463 gold badges16 silver badges19 bronze badges
3
You can pipe it through awk and make it echo the first word
echo * | head -n1 | awk '{print $1;}'
or you cut the string up and select the first word:
echo * | head -n1 | cut -d " " -f1
or you pipe it thorugh sed and have it remove everything but the first word
echo * | head -n1 | sed -e 's/s.*$//'
Added the | head -n1
to satisfy nitpickers. In case your string contains newlines | head -n1
will select the first line first before the important commands select the first word from the string passed to it.
answered Feb 24, 2013 at 19:08
BananguinBananguin
7,7662 gold badges23 silver badges56 bronze badges
7
Assuming a posixy shell (/bin/sh
or /bin/bash
can do this)
all=$(echo *)
first=${all%% *}
The construct ${all%% *}
is an example of substring removal. The %%
means delete the longest match of *
(a space followed by anything) from the right-hand end of the variable all
. You can read more about string manipulation here.
This solution assumes that the separator is a space. If you’re doing this with file names then any with spaces will break it.
answered May 6, 2015 at 10:55
starfrystarfry
7,1126 gold badges46 silver badges68 bronze badges
3
Assuming that you really want the first filename and not the first word, here’s a way that doesn’t break on whitespace:
shopt -s nullglob
files=(*)
printf '%sn' "${files[0]}"
answered Feb 24, 2013 at 12:07
Chris DownChris Down
120k22 gold badges263 silver badges260 bronze badges
12
You can use the positional parameters
set -- *
echo "$1"
answered Feb 24, 2013 at 12:39
glenn jackmanglenn jackman
82.6k14 gold badges115 silver badges166 bronze badges
2
Check one of the following alternatives:
$ FILE=($(echo *))
$ FILE=$(echo * | grep -o "^S*")
$ FILE=$(echo * | grep -o "[^ ]*")
$ FILE=$(find . -type f -print -quit)
Then you can print it via echo $FILE
.
See also: grep
the only first word from output?
answered Oct 16, 2015 at 13:14
kenorbkenorb
19.8k14 gold badges137 silver badges162 bronze badges
Getting the whole first file name:
shopt -s nullglob
printf '%s00' * | grep -z -m 1 '^..*$'
printf '%s00' * | ( IFS="" read -r -d "" var; printf '%sn' "$var" )
answered Mar 21, 2016 at 14:27
Another approach is to list all the file names as an array, and then index the array for the first element:
STRARRAY=($(echo *))
FIRST=${STRARRAY[0]}
answered Apr 3, 2022 at 21:59
1
I am using below command to get first word of file
awk '{print $1}' myFile
but it is printing first word of all lines
muru
190k52 gold badges465 silver badges716 bronze badges
asked Sep 13, 2015 at 21:08
awk
will run the commands (except BEGIN
/END
blocks, etc.) on every line. So… exit after processing the first line:
awk '{print $1; exit}' /some/file
Or qualify to include only the first line:
awk 'FNR == 1 {print $1}' /some/file #still runs the test on all lines
answered Sep 13, 2015 at 21:12
murumuru
190k52 gold badges465 silver badges716 bronze badges
You can use sed
:
sed -nr '1s/^([^ ]+).*/1/p' file.txt
-
1
at the start of the substitution pattern indicates that we are working only on the first line of the file -
[^ ]+
will find the first space separated word, we are putting it into a group so that we can refer to it later in the substitution pattern -
s/^([^ ]+).*/1/
will replace the first line with only the first word
answered Sep 13, 2015 at 21:17
heemaylheemayl
89.4k20 gold badges197 silver badges264 bronze badges
Different approach without awk
or sed
:
tr ' ' 'n' < file.txt | head -n1
answered Apr 9, 2021 at 12:42
pLumopLumo
25.8k2 gold badges57 silver badges87 bronze badges
10 More Discussions You Might Find Interesting
1. Shell Programming and Scripting
Remove last word of a string?
Hello
I have a string that may or may not have 4 dots.
The string is actualy a file within a folder, where multiple files are located.
Files may look like:
# ls *
creds:
192.168.10.110 someserver
shares:
192.168.10.110.Public someserver.sharefolder
#
I want to fill 2 variables,… (1 Reply)
Discussion started by: sea
2. Shell Programming and Scripting
Deleting a word from a string
Hello All,
I have a string like below —
/LDCA20/rel/prod/libina.a
I want to delete «libina.a» which is at the end.How can I do this ??
Thanks in advance
Regards,
Anand (10 Replies)
Discussion started by: anand.shah
3. Shell Programming and Scripting
How can we get the character before and after a word in a string?
Hi friends,
I am working in a korn shell. i want to know the command which gives me the previous one character and next one character of a given keyword in a string?
for exmaple:
input string: /bin/dir/folder1/.proc_name^folderone
Keyword: proc_name
output : .^
… (10 Replies)
Discussion started by: neelmani
4. Shell Programming and Scripting
Identifying entries based on 2 fields in a string.
Hi Guys,
I’m struggling to use two fields to do a duplicate/ unique by output.
I want to look IP addresses assigned to more than one account during a given period in the logs. So duplicate IP and account > 1 then print all the logs for that IP. I have been Using AWK (just as its installed… (3 Replies)
Discussion started by: wabbit02
5. Shell Programming and Scripting
Replace a word in a string starting with another word
Hi All,
I have a file in which a number of lines are starting with similar first word but different next words.
I want to replace the any nth word(not 1st or 2nd) with another word.
Eg:- My file contains are like this:-
Ram is a boy.
Ram is a good boy.
Ram plays cricket.
Here I want to… (2 Replies)
Discussion started by: mukeshbaranwal
6. Shell Programming and Scripting
grep part of word or Another word from a string
Hi all,
FileOne
family balance >>>>>
0 0
0 0
java.io.FileNotFoundException: Settings.xml (No such file or directory)
at java.io.FileInputStream.open(Native Method)
..
….
…..
…..
java.lang.NullPointerException
…
…..
……
Stacktrace:
at… (2 Replies)
Discussion started by: linuxadmin
7. Shell Programming and Scripting
Replace a word After a string.
Hello Gurus,
I have a file which has foll contents scattered:
,TotUnasgndNetAmt
FROM DEV_EIS_T.Wkly_SO_CCD_MOSumSnpsht
WHERE
CalDayRunDt = ‘2010-07-21′
UNION ALL
SELECT
CalDayRunDt
,BusWkCd
,’N’
I want to replace 2010-07-21 that starts after ‘ and ends before… (8 Replies)
Discussion started by: indrajit_u
8. Shell Programming and Scripting
Identifying a string from a set of files and printing to a new file
Dear All,
I’m an amateur to writing scripts and need to do the following
Need to read all files with a .log extension in a directory and identify the value for username i.e. all files have something like username = John. Once this is read, I need to print this value to a new file. The new file… (2 Replies)
Discussion started by: Kelly_B
9. UNIX for Dummies Questions & Answers
How to get the location of word in a string
How to use instr function in awk ?
to get the location
a) for example instr(‘productiondata_12′,’data’,1) to get the location of data using awk.
b) for example instr(‘sampledata_rev_12′,’rev’,1) to get the location of data
and reaplce with «org» using awk.
can anyone help
… (3 Replies)
Discussion started by: Vrgurav
10. UNIX for Dummies Questions & Answers
How to get the n-th word in a string
Hi,
Suppose I do this:
$ wc file.txt
96 333 6629 file.txt
and I want to get the 3rd word from the left (i.e. get the string 6629) and check its value.
What do I do?
Thanks (3 Replies)
Discussion started by: GMMike
- Печать
Страницы: [1] Вниз
Тема: bash — получить первое слово в строке (Прочитано 13705 раз)
0 Пользователей и 1 Гость просматривают эту тему.
Señor_Gaga
К примеру имеется переменная $STR = «слово1 далее некоторый текст»
Как выделить слово1 и присвоить его переменной FIRST_WORD ?
victor00000
echo "слово0 слово1 слово2" | sed 's/слово1/FIRST_WORD/g'
Protopopulus
echo "слово0 слово1 слово2" | sed 's/слово1/FIRST_WORD/g'
Ерунда какая-то…
Шляпа, делай так:
FIRST_WORD=`echo ${STR} | awk '{print $1}'`
Результат:
protopopulus@sofocl:~$ STR='qwe qwee qweeee'
protopopulus@sofocl:~$ echo $STR
qwe qwee qweeee
protopopulus@sofocl:~$ FIRST_WORD=`echo ${STR} | awk '{print $1}'`
protopopulus@sofocl:~$ echo $FIRST_WORD
qwe
protopopulus@sofocl:~$
Если ты владеешь знаниями, то и знания владеют тобой. (с) Protopopulus
Señor_Gaga
ArcFi
Ещё пара вариантов:
$ STR="слово1 далее некоторый текст" ; echo "$STR" | cut -d' ' -f1
слово1
$ STR="слово1 далее некоторый текст" ; echo "${STR%% *}"
слово1
- Печать
Страницы: [1] Вверх