bash split string with awk

# Basic syntax:
awk '{split($column_to_split,array_name,"delimiter"); print a[index]}'
# Where:
#	- the array_name is usually shortened to a
#	- delimiter is the delimiter you want to split the string by
#	- index is the index of the string "piece" you want to work with

# Example usage:
# Say you want to split the following string by underscores and print
# the third item:
string_containing_CODE_to_pentagon
echo "string_containing_CODE_to_pentagon" | awk '{split($0,a,"_"); print a[3]}'
--> CODE

# Example usage:
# Say you have input_file.txt that contains two columns and you want to 
# split the second column by | and then by _ and then print the second 
# string of the final split:
cat file.txt
--> code_1	12|ab_cd|34_ef
	code_2	ef_56|gh_78_ij

awk '{split($2, a, "|");  split(a[2],b,"_"); print b[2]}' file.txt
--> cd
	78

3.6
10

                                    Just use function split in awk command to split a line into an array 'a'
using a choosen string as delimiter as for example ", " in next use case:
echo "hi, bye, hey" | awk '{split($0,a,", "); print a[3],a[2],a[1]}'

3.6 (10 Votes)
0
4.71
7
Libby 120 points

                                    Just use function split in awk command to split a line into an array 'a'
using a choosen string as delimiter as for example ", " in next use case:
echo "hi, bye, hey" | awk '{split($0,a,", "); print a[3],a[2],a[1]}'

4.71 (7 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source