Linux get first line

How can I retrieve the first word of the output of a command in Bash?

I have a command, for example: echo «word1 word2» . I want to put a pipe ( | ) and get «word1» from the command.

13 Answers 13

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 '' # 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.

This doesn’t work if the string is e.g. «firstWord, secondWord» as that awk command delimiters by space

@RogerOba That wasn’t the OP’s question, but you can use -F»,» to override the default field separator (a space) with a comma.

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.

+1 for using only shell built-ins and stdin . @Matt M. — means stdin , so $string is being passed in as stdin . stdin is whitespace-separated into arguments $1 , $2 , $3 , etc. — just like when a Bash program evaluates arguments (e.g. check $1 , $2 , etc.), this approach takes advantage of the shell’s tendency to split the stdin into arguments automatically, removing the need for awk or cut .

word1=$(IFS=» » ; set — $string ; echo $1) Set IFS to correctly recognize the space between the words. Wrap in parentheses to avoid clobbering the original content of $1.

Good answer, because this is valid not only for Bash, but even for the traditional Bourne shell as well.

I think one efficient way is the use of Bash arrays:

array=( $string ) # Do not use quotes in order to allow word expansion echo $ # 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 "$" ; done 

Use the while syntax to retrieve every first word at each line. Otherwise, use Boontawee Home approach. Also, please note that echo «$» has been quoted to prevent expansion as noticed by gniourf-gniourf.

If you try to access an index of array which is greater than the number of words, then you won’t get an error. You will just get an empty line

This has the advantage that is not using external commands and leaves the $1, $2, etc. variables intact.

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 $ word1 string='word1 word2 ' echo $ 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 .

Читайте также:  Calculate linux установка wine

With AWK it is really easy to pick any word you like ( $1 , $2 , etc.).

If you are sure there are no leading spaces, you can use Bash parameter substitution:

$ string="word1 word2" $ echo $ 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" $ [[ $ =~ \ *([^\ ]*) ]] $ echo $ word1 

I wondered how several of the top answers measured up in terms of speed. I tested the following:

string=". "; set -- $string; echo $1 

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") 

Weird that you could measure 3 in dash, since dash doesn’t support arrays ( read -a is invalid in dash).

Yeah that is weird. I ruled that one out, did the speed tests, then thought «why’d I leave that one out» and added it in. Removing it now, and I may rerun things later to make sure I didn’t have some mistake

echo "word1 word2" | cut -f 1 -d " " 

cut cuts the first field ( -f 1 ) from a list of fields delimited by the string » » ( -d » » ).

that’s one way, but your cut statement won’t distinguish multiple spaces in between words if he wants to get word2 later on

    If string is in a variable:

string="word1 word2" read -r first _  
printf '%s\n' "word1 word2" "line2" |
printf '%s\n' "word1 word2" "worda wordb" | while read -r first _; do printf '%s\n' "$first"; done 

These work if there are leading spaces:

As Perl incorporates AWK's functionality, this can be solved with Perl too:

echo " word1 word2" | perl -lane 'print $F[0]' 

That actually works, even with the leading zero, but an explanation would be in order. Please respond by editing your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).

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 

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.

Источник

Linux Commands: How to Print the First Lines of a File in Linux

Learn how to print the first lines of a file in Linux using commands like head, sed, awk, and cut. Explore helpful tips and best practices for manipulating files and data.

  • Using the head command to display the beginning of a file
  • Using the sed command to read and print specific lines of a file
  • How to print first n lines in a file in Linux Shell terminal
  • Using the awk command to print the first line of a file
  • Using the head command to print the first few lines of multiple files or characters of a file
  • Other commands like tail, cut, and awk can also be used to manipulate and display specific parts of a file
  • Other useful code examples for printing the first lines of a file in Linux
  • Conclusion
  • How do I print the first line of a file in Linux?
  • How do I print the first 5 lines of a file in Linux?
  • How do I get the first 100 lines of a file in Unix?
  • How do you display the first 3 lines of a file in Unix?

The Linux operating system is well-known for its powerful command line interface and its ability to manipulate files and data with ease. Among the wide range of commands that Linux offers, the ability to print the first few lines of a file can be extremely helpful for quickly previewing or checking the contents of a file. In this article, we will explore various ways to print the first lines of a file in Linux using commands like head, sed, awk, and cut, as well as some helpful tips and best practices.

Using the head command to display the beginning of a file

The head command is a standard Unix command that can be used to display the beginning of a text file or piped data. By default, the head command displays the first ten lines of the specified files. To print a specific number of lines , use the -n or –lines option followed by the desired number. Here are some examples:

This command will display the first 10 lines of the file.txt.

This command will display the first 5 lines of the file.txt.

Using the sed command to read and print specific lines of a file

The sed command is a stream editor that can be used to perform basic text transformations on an input stream. The ‘p’ command in sed can be used to read and print specific lines of a file. Here are some examples:

This command will print the 5th line of the file.txt.

This command will print lines 5 to 10 of the file.txt.

How to print first n lines in a file in Linux Shell terminal

Using the awk command to print the first line of a file

The awk command is a versatile tool for processing and manipulating text files. The NR variable in awk can be used to select specific lines of a file. Here is an example:

This command will print the first line of the file.txt.

Using the head command to print the first few lines of multiple files or characters of a file

The head command can be used to print the first few lines of each specified file or of the standard input. The -c or –bytes option can be used to print the first n characters of a file. Here are some examples:

This command will print the first 10 lines of both file1.txt and file2.txt.

This command will print the first 100 characters of the file.txt.

Other commands like tail, cut, and awk can also be used to manipulate and display specific parts of a file

Apart from the above-mentioned commands, there are other commands like tail, cut, and awk that can be used to manipulate and display specific parts of a file. Here are some examples:

This command will display the last 10 lines of the file.txt.

This command will print the first column of the csv file.txt.

Other useful code examples for printing the first lines of a file in Linux

In Shell , in particular, only show first lines linux code sample

In Shell , print first lines of file linux code sample

With the flag -n | N, the head command prints out the first N lines of file(s)head -n 7 file.txt #Prints first 7 lines of file.txt

In Shell case in point, linux get first line of file code sample

# credit to Stack Overflow user in the source linkhead -1 your_file

Conclusion

In conclusion, printing the first lines of a file in Linux can be achieved using various commands like head, sed, awk, and cut, as well as some helpful tips and best practices. It is important to be familiar with the command line interface and basic syntax in order to use these commands effectively. Using regular expressions and other advanced features can provide even more flexibility and power. Understanding and using these commands can be especially useful for developers, system administrators, and other technical users. So, if you are looking for a quick and easy way to preview the contents of a file in Linux, try using one of these commands and see how it works for you.

Источник

Linux: Extract the first line of a file

I am working with OpenWrt and a very small amount of space. Trying to extract the first line from a file. The line needs to go into a variable and be removed from the file. I can use head to put it into a variable but can't use tail because as far as I understand I would have to do tail file > newFile and I do not have room for that second file. Does some one know if a better technic?

You're not going to be able to avoid reading and rewriting the entire file. Perhaps this can be done in-place, but most tools don't because a failure will cause a partial result. What file is this? Perhaps there is another solution that doesn't involve the actual removal of the line.

It's a raw text file in a specific format that I am getting from curl and pushing to hardware via Netcat

@jofel That's a great idea. How do I do that? When I put the Curl response into a variable it losses the "returns" so it's all on the first line.

6 Answers 6

Edit: you can't use my old answer (see below) with OpenWrt since OpenWrt doesn't ship with ed . What a shame. So here are two methods:

The vi way

vi is a genuine editor too, so the following will work:

vi -c ':1d' -c ':wq' file > /dev/null 

We open the file with vi , and use the commands :1d to delete the first line and :wq to save and quit, redirecting all output to /dev/null . Cool, clean, short and simple.

Oh, you will of course run:

before running this vi command to get the first line of the file into the variable firstline .

Note. On a system with very little memory, and when file is huge, this method fails.

The dd way

dd is a cool tool for this. The dd methods given in other answers are really great, yet they rely on the truncate utility which does not ship with OpenWrt. Here's a workaround:

firstline=$(head -n1 file) linelength=$(head -n1 file | wc -c) newsize=$(( $(wc -c < file) - $linelength )) dd if=file of=file bs=1 skip=$linelength conv=notrunc dd if=/dev/null of=file bs=1 count=0 seek=$newsize 

This will work even with huge files and very little memory! The last dd command plays the role of the truncate command given in the other answers.

firstline=$(printf '%s\n' 1p d wq | ed -s file.txt) 

At each call, you'll get the first line of the file file.txt in the variable firstline , and this line is removed from the file.

Источник

Оцените статью
Adblock
detector