如何使用sed替换正则表达式捕获组?

时间:2015-05-25 04:42:05

标签: regex bash sed

我有一个包含许多分散文件路径的大文件,看起来像

lolsed_bulsh.png

我想在扩展路径前添加这些文件名,如:

/full/path/lolsed_bullsh.png

我很难匹配和捕捉这些。目前我正在尝试各种变体:

cat myfile.txt| sed s/\(.+\)\.png/\/full\/path\/\1/g | ack /full/path

我认为sed有一些正则表达式或捕获组行为我不理解

3 个答案:

答案 0 :(得分:19)

使用<div class="clear">First name:<br> <input type="text" name="firstname"><br> </div>

进行正则表达式更改+
*

打印:

sed -E "s/(.*)\.png/\/full\/path\/\1/g" <<< "lolsed_bulsh.png"

注意: 非标准 /full/path/lolsed_bulsh 选项是为了避免转义-E(

答案 1 :(得分:7)

package com.betech.bbqv2.jsonparse; import android.app.ActionBar; import com.betech.bbqv2.login.AndroidPHPConnectionDemo; import com.betech.bbqv2.main.AddActivity; import com.betech.bbqv2.main.CheckLogin; import com.betech.bbqv2.main.DataListView; import com.betech.bbqv2.main.MainActivity; import com.betech.bbqv2.main.OrderHistory; import com.betech.bbqv2.R; import com.betech.bbqv2.main.SingleContactActivity; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.List; import org.json.JSONObject; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.Button; import android.widget.GridView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class countrymain extends Activity { ListView mListView; private String catid; private String companycode="bbq"; private SharedPreferences loginPreferences; private SharedPreferences.Editor loginPrefsEditor; private SharedPreferences tmploginPreferences; private SharedPreferences.Editor tmploginPrefsEditor; String matchguest=""; private ActionBar actionBar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // requestWindowFeature(Window.FEATURE_NO_TITLE); // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.country_main); actionBar = getActionBar(); actionBar.show(); getActionBar().setIcon(R.drawable.actionbar_icon); getActionBar().setDisplayShowTitleEnabled(false); loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE); loginPrefsEditor = loginPreferences.edit(); tmploginPreferences = getSharedPreferences("tmploginPrefs", MODE_PRIVATE); tmploginPrefsEditor = tmploginPreferences.edit(); String login1 = loginPreferences.getString("username", ""); String login2 = tmploginPreferences.getString("tmpusername", ""); String match="nomatch"; login1=login1.toLowerCase(); login2=login2.toLowerCase(); if(login1.equalsIgnoreCase("guest") || login2.equalsIgnoreCase("guest")){ matchguest="guest"; }else{ matchguest="noguest"; } catid=getIntent().getExtras().getString("cat"); String strUrl = "http://myweb/bbq/mobile.php?catid="+catid+"&matchguest="+matchguest; DownloadTask downloadTask = new DownloadTask(); // Starting the download process downloadTask.execute(strUrl); // Getting a reference to ListView of activity_main mListView = (ListView) findViewById(R.id.lv_countries); mListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Open the browser here HashMap<String,Object> map = (HashMap<String, Object>) parent.getItemAtPosition(position); TextView foodcode = ((TextView) mListView.findViewById(R.id.foodcode)); TextView foodname = ((TextView) mListView.findViewById(R.id.foodname)); TextView fooddesc1 = ((TextView) mListView.findViewById(R.id.fooddesc1)); TextView fooddesc2 = ((TextView) mListView.findViewById(R.id.fooddesc2)); TextView foodprice = ((TextView) mListView.findViewById(R.id.foodprice)); // Toast.makeText(countrymain.this, "label is="+map.get("country") // , Toast.LENGTH_SHORT).show(); // Toast.makeText(countrymain.this, "label is="+quantity.getText().toString() //, Toast.LENGTH_SHORT).show(); //TextView quantity = ((TextView) v.findViewById(R.id.value)); Intent in = new Intent(getApplicationContext(), SingleContactActivity.class); in.putExtra("foodcode", map.get("foodcode").toString()); in.putExtra("foodname", map.get("foodname").toString()); in.putExtra("fooddesc1", map.get("fooddesc1").toString()); in.putExtra("fooddesc2", map.get("fooddesc2").toString()); in.putExtra("foodprice", map.get("foodprice").toString()); in.putExtra("imagepath", map.get("flag_path").toString()); startActivity(in); } }); // public void onItemClick(AdapterView<?> parent, View v, // int position, long id) { // mListView.setOnItemClickListener(new OnItemClickListener() { // public void onItemClick(AdapterView adapterView, View view, int position, long id) { // SimpleAdapter adapter = (SimpleAdapter) adapterView.getAdapter(); // ListView currentLv = (ListView) view; // Object item = adapter.getItem(position); //Do some more stuff here and launch new activity //} //}); } /** A method to download json data from url */ private String downloadUrl(String strUrl) throws IOException{ String data = ""; InputStream iStream = null; try{ URL url = new URL(strUrl); // Creating an http connection to communicate with url HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // Connecting to url urlConnection.connect(); ///////////////////////////////Newly added int responseCode = urlConnection.getResponseCode(); String responseMessage = urlConnection.getResponseMessage(); // InputStream is = null; Log.d("response code=",String.valueOf(responseCode)); if (responseCode >= 400) { iStream = urlConnection.getErrorStream(); } else { //is = urlConnection.getInputStream(); iStream = urlConnection.getInputStream(); } ///////////////////////////////////////////////// // Reading data from url // iStream = urlConnection.getInputStream();<---original BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); StringBuffer sb = new StringBuffer(); String line = ""; while( ( line = br.readLine()) != null){ sb.append(line); } data = sb.toString(); br.close(); }catch(Exception e){ Log.d("Exception while downloading url", e.toString()); }finally{ iStream.close(); } return data; } /** AsyncTask to download json data */ private class DownloadTask extends AsyncTask<String, Integer, String>{ String data = null; @Override protected String doInBackground(String... url) { try{ data = downloadUrl(url[0]); }catch(Exception e){ Log.d("Background Task",e.toString()); } return data; } @Override protected void onPostExecute(String result) { // The parsing of the xml data is done in a non-ui thread ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask(); // Start parsing xml data listViewLoaderTask.execute(result); } } /** AsyncTask to parse json data and load ListView */ private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{ JSONObject jObject; // Doing the parsing of xml data in a non-ui thread @Override protected SimpleAdapter doInBackground(String... strJson) { try{ //Toast.makeText(countrymain.this, "URL="+strJson[0], Toast.LENGTH_SHORT).show(); jObject = new JSONObject(strJson[0]); CountryJSONParser countryJsonParser = new CountryJSONParser(); countryJsonParser.parse(jObject); }catch(Exception e){ Log.d("JSON Exception1",e.toString()); } // Instantiating json parser class CountryJSONParser countryJsonParser = new CountryJSONParser(); // A list object to store the parsed countries list List<HashMap<String, Object>> countries = null; try{ // Getting the parsed data as a List construct countries = countryJsonParser.parse(jObject); }catch(Exception e){ Log.d("Exception",e.toString()); } // Keys used in Hashmap //String[] from = { "country","flag","details"}; String[] from = { "foodcode","foodname","fooddesc1","fooddesc2","foodprice","flag"}; // Ids of views in listview_layout // int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details}; int[] to = { R.id.foodcode,R.id.foodname,R.id.fooddesc1, R.id.fooddesc2,R.id.foodprice,R.id.iv_flag}; // Instantiating an adapter to store each items // R.layout.listview_layout defines the layout of each item SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to); // CheckLogin checknow = new CheckLogin (); // String guestnot=checknow.checklogin(); // Log.d("Match=",guestnot); // if(guestnot.equals("match")){ // //} return adapter; } /** Invoked by the Android on "doInBackground" is executed */ @Override protected void onPostExecute(SimpleAdapter adapter) { // Setting adapter for the listview mListView.setAdapter(adapter); // Toast.makeText(countrymain.this, "label is="+adapter.getCount() // , Toast.LENGTH_SHORT).show(); for(int i=0;i<adapter.getCount();i++){ HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i); String imgUrl = (String) hm.get("flag_path"); ImageLoaderTask imageLoaderTask = new ImageLoaderTask(); HashMap<String, Object> hmDownload = new HashMap<String, Object>(); hm.put("flag_path",imgUrl); hm.put("position", i); // Starting ImageLoaderTask to download and populate image in the listview imageLoaderTask.execute(hm); } } } /** AsyncTask to download and load an image in ListView */ private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{ @Override protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) { InputStream iStream=null; String imgUrl = (String) hm[0].get("flag_path"); int position = (Integer) hm[0].get("position"); URL url; try { url = new URL(imgUrl); // Creating an http connection to communicate with url HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // Connecting to url urlConnection.connect(); // Reading data from url iStream = urlConnection.getInputStream(); // Getting Caching directory File cacheDirectory = getBaseContext().getCacheDir(); // Temporary file to store the downloaded image File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".jpg"); // The FileOutputStream to the temporary file FileOutputStream fOutStream = new FileOutputStream(tmpFile); // Creating a bitmap from the downloaded inputstream Bitmap b = BitmapFactory.decodeStream(iStream); // Writing the bitmap to the temporary file as png file b.compress(Bitmap.CompressFormat.PNG,100, fOutStream); // Flush the FileOutputStream fOutStream.flush(); //Close the FileOutputStream fOutStream.close(); // Create a hashmap object to store image path and its position in the listview HashMap<String, Object> hmBitmap = new HashMap<String, Object>(); // Storing the path to the temporary image file hmBitmap.put("flag",tmpFile.getPath()); // Storing the position of the image in the listview hmBitmap.put("position",position); // Returning the HashMap object containing the image path and position return hmBitmap; }catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(HashMap<String, Object> result) { // Getting the path to the downloaded image String path = (String) result.get("flag"); // Getting the position of the downloaded image int position = (Integer) result.get("position"); // Getting adapter of the listview SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter(); // Getting the hashmap object at the specified position of the listview HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position); // Overwriting the existing path in the adapter hm.put("flag",path); // Noticing listview about the dataset changes adapter.notifyDataSetChanged(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); //menuInflater.inflate(R.layout.menu, menu); menuInflater.inflate(R.menu.activity_main_actions, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // action with ID action_refresh was selected case R.id.action_setting1s: Intent m= new Intent(getApplicationContext(),MainActivity.class); startActivity(m); break; // action with ID action_settings was selected case R.id.action_setting2s: Intent j = new Intent(getApplicationContext(),DataListView.class); startActivity(j); break; case R.id.action_setting3s: // Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT) // .show(); Intent k = new Intent(getApplicationContext(),OrderHistory.class); startActivity(k); break; case R.id.action_setting4s: // Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT) // .show(); Intent intent = new Intent(getApplicationContext(),AndroidPHPConnectionDemo.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); // moveTaskToBack(true); // android.os.Process.killProcess(android.os.Process.myPid()); //System.exit(0); break; default: break; } return true; } } 使用POSIX BRE和BRE doesn't support one or more quantifier +。量词sed仅为supported in POSIX ERE。但是,POSIX sed uses BRE and has no option to switch to ERE

如果您想保持可移植性,请使用+模拟..*

或者,如果您可以假设代码始终在GNU sed上运行,则可以使用GNU扩展.+。或者,您也可以使用GNU扩展.\+标志切换到POSIX ERE。 higuaro's answer中的-r标记为an undocumented flag for compatibility with BSD sed,效果相同。

答案 2 :(得分:2)

通过选择不同的分隔符(和-E选项)来节省一些转义,例如:

cat myfile.txt | sed -E "s|(..*)\.png|/full/path/\1|g" | ack /full/path